﻿using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;

namespace ConfigDemo.Middleware;
public class ExceptionMiddleware
{
    private readonly RequestDelegate _next;
    private IWebHostEnvironment _webHostEnvironment;
    private readonly ILogger<ExceptionMiddleware> _logger;
    public ExceptionMiddleware(
        RequestDelegate next
        , IWebHostEnvironment webHostEnvironment
        , ILogger<ExceptionMiddleware> logger
        )
    {
        _next = next;
        _webHostEnvironment = webHostEnvironment;
        _logger = logger;
    }

    public async Task Invoke(HttpContext context)
    {
        try
        {
            await _next.Invoke(context);
            var features = context.Features;
        }
        catch (Exception e)
        {
            await HandleException(context, e);
        }
    }

    private async Task HandleException(HttpContext context, Exception e)
    {
        context.Response.StatusCode = 500;
        context.Response.ContentType = "text/json;charset=utf-8;";
        string error = "";
        _logger.LogError($"/n错误信息：{e.Message},/n堆栈信息{e.StackTrace}");
        if (_webHostEnvironment.IsDevelopment())
        {
            error = e.Message;
        }
        else
        {
            error = "抱歉，出错了,"+e.Message;
        }
        await context.Response.WriteAsync(error);
    }
}